﻿#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    manager=new QNetworkAccessManager(this);
    connect(manager,&QNetworkAccessManager::finished,this,&Dialog::replyFinished);

    ping();
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::get(const QString &url)
{
    QNetworkReply *reply =manager->get(QNetworkRequest(QUrl(url)));
    replyMap.insert(reply, R_Get);
}

void Dialog::ping()
{
    if(!QFile::exists(CFG_FILE))
        qCritical() << QStringLiteral("致命错误，配置文件不存在，程序无法启动");

    QSettings cfg(CFG_FILE,QSettings::IniFormat);
    QString host=cfg.value("Whisper/host").toString();
    QString entry=cfg.value("Whisper/entry").toString();
    base_url = "http://" + host + entry;

    pingReply = manager->get(QNetworkRequest(QUrl(base_url)));
    connect(pingReply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(down()));
}

void Dialog::down()
{
    pingReply->deleteLater();
    qInfo() << QStringLiteral("无法连接到服务器，程序退出");
    QMessageBox::StandardButton btn=
            QMessageBox::critical(this,QStringLiteral("连接失败"),QStringLiteral("无法连接到服务器，程序现在退出"));
    if(btn == QMessageBox::Ok)
        this->close();
}

void Dialog::on_submit_clicked()
{
    key=ui->inKey->text().trimmed();
    if(key.isEmpty())
        return;

    value=ui->inValue->text().trimmed();
    if(value.isEmpty())
    {
        url=base_url + "del/" +  key;
    }
    else
        url=base_url + key + QString("/") + value;

    get(url);
    ui->inKey->clear();
    ui->inValue->clear();
}

void Dialog::on_ask_clicked()
{
    key=ui->inAsk->text().trimmed();
    if(key.isEmpty())
        return;

    url = base_url + key;
    get(url);
}

void Dialog::replyFinished(QNetworkReply *reply)
{
    RemoteRequest request=replyMap.value(reply);

    switch (request) {
    case R_Get:
        Pie pie(reply->readAll());
        QJsonValue value=pie.getValue("reply");
        if(value.isString())
            ui->reply->setText(value.toString());
        else if(value.isDouble())
            ui->reply->setText(QString::number(value.toDouble()));
        break;
    }
}
